﻿using System.Text;

namespace Yz.Core.Extensions
{
    /// <summary>
    /// 实现Base64加密解密
    /// </summary>
    public static class Base64Extension
    {

        #region 加密
        /// <summary>
        /// Base64加密
        /// </summary>
        /// <param name="codeName">加密采用的编码方式</param>
        /// <param name="source">待加密的明文</param>
        /// <returns></returns>
        public static string ToEncodeBase64(this string value, Encoding encode)
        {
            string encodeString = "";
            byte[] bytes = encode.GetBytes(value);
            try
            {
                encodeString = Convert.ToBase64String(bytes);
            }
            catch
            {

            }
            return encodeString;
        }

        /// <summary>
        /// Base64加密，采用utf8编码方式加密
        /// </summary>
        /// <param name="source">待加密的明文</param>
        /// <returns>加密后的字符串</returns>
        public static string ToEncodeBase64(this string value)
        {
            return value.ToEncodeBase64(Encoding.UTF8);
        }
        #endregion

        #region 解密
        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="codeName">解密采用的编码方式，注意和加密时采用的方式一致</param>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public static string ToDecodeBase64(this string value, Encoding encode)
        {
            byte[] bytes = Convert.FromBase64String(value);
            string decode;
            try
            {
                decode = encode.GetString(bytes);
            }
            catch
            {
                decode = value;
            }
            return decode;
        }

        /// <summary>
        /// Base64解密，采用utf8编码方式解密
        /// </summary>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public static string ToDecodeBase64(this string value)
        {
            return value.ToDecodeBase64(Encoding.UTF8);
        }
        #endregion
    }
}
